<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;

        }

        h1 {
            position: absolute;
            top: 0;
            left: 0;
        }


        #canvas {
            margin: 0 auto;
            position: relative;
            display: block;
        }
    </style>
</head>

<body>
    <h1>用canvas做的画板，可直接用鼠标左键在空白区域作画</h1>
    <canvas id="canvas"></canvas>
    <script>
        let canvas = document.getElementById("canvas");
        canvas.width = document.documentElement.clientWidth
        canvas.height = document.documentElement.clientHeight

        let ctx = canvas.getContext("2d");
        let painting = false
        let last

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.lineWidth = 10
        ctx.lineCap = 'round'
        function drawLine(x1, y1, x2, y2) {
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
        }


        let isTouchDevice = 'ontouchstart' in document.documentElement;
        if (isTouchDevice) {
            canvas.ontouchstart = (e) => {
                let x = e.touches[0].clientX
                let y = e.touches[0].clientY
                last = [x, y]
            }
            canvas.ontouchmove = (e) => {
                let x = e.touches[0].clientX
                let y = e.touches[0].clientY
                drawLine(last[0], last[1], x, y)
                last = [x, y]

            }
        } else {
            canvas.onmousedown = (e) => {
                painting = true
                last = [e.clientX, e.clientY]
            }
            canvas.onmousemove = (e) => {
                if (painting === true) {
                    drawLine(last[0], last[1], e.clientX, e.clientY)
                    last = [e.clientX, e.clientY]
                } else {
                }
            }
            canvas.onmouseup = () => {
                painting = false
            }
        }



    </script>
</body>

</html>